#pragma once

#include "../SegmentActions.h"

namespace My {

inline Segment * SegmentSet::GetActiveSegmentPtr()
{
	int i = GetActiveSegment();
	return i == -1 ? 0 : &GetSegment(i);
}

template <typename S>
void TypedSegmentSet<S>::EraseSelection()
{
	int active = GetActiveSegment();
	if (active == -1)
		return;
	GetDoc().Perform(new DeleteSegment<S>(* this,	Size(active)));
}

template <typename S>
void TypedSegmentSet<S>::MoveSelection(int index)
{
	int active = GetActiveSegment();
	if (active == -1)
		return;
	GetDoc().Perform(new MoveSegment<S>(* this, Size(active), index));
}

template <typename S>
SegmentUpdate<S>::SegmentUpdate(TypedSegmentSet<S> & s)
	: m_Owner(s)
{
	m_Active = m_Owner.GetActiveSegment();
	m_pActive = (m_Active == -1 ? 0 : &m_Owner.GetSegment(m_Active));
	m_Owner.SetActiveSegment(-1);
}

template <typename S>
SegmentUpdate<S>::~SegmentUpdate()
{
	m_Owner.DispatchEvent(SegmentSet::Change(m_Owner));
	for (Size i = 0; i < m_Owner.GetSegmentCount(); ++i)
		if (&m_Owner.GetSegment(i) == m_pActive) {
			m_Owner.SetActiveSegment(int(i));
			return;
		}
	m_Owner.SetActiveSegment(m_Active);
}

template <typename S>
void SegmentUpdate<S>::Insert(Size index, SegmentType * ptr)
{
	m_Owner.Insert(index, ptr);
}

template <typename S>
S * SegmentUpdate<S>::Erase(Size index)
{
	return m_Owner.Erase(index);
}

} // My
